package com.nxn.core.utils.web;

import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;

import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class TimeConverter extends DefaultTypeConverter {
	private static final DateFormat[] ACCEPT_DATE_FORMATS = {
			new SimpleDateFormat("HH:mm:ss") }; // 支持转换的时间格式

	@Override 
	public Object convertValue(Map context, Object value, Class toType) { 
		if (toType == Time.class) {  //浏览器向服务器提交时，进行String to Time的转换 
			String[] params = (String[])value; 
			String dateString = params[0]; 
			for (DateFormat format : ACCEPT_DATE_FORMATS) { 
				try { 
					return new Time(format.parse(dateString).getTime());//遍历日期支持格式，进行转换 
				} catch(Exception e) { 
					continue; 
				}
			} 
			return null; 
		}  else if (toType == String.class) {   //服务器向浏览器输出时，进行Date to String的类型转换 
			Time time = (Time)value; 
			return ACCEPT_DATE_FORMATS[0].format(time);
		} 
		
		return null; 
	}
}
